package com.young.springdemo.config.red;

import com.young.springdemo.jpa.entity.RedTeacherEntity;
import com.young.springdemo.jpa.repository.RedTeacherRepository;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @program: springdemo
 * @description 红名单人员的处理
 * @author: Young
 * @create: 2020-05-31 15:39
 **/
@Configuration
@Aspect
@Slf4j
public class RedPersonConfig {

    @Autowired
    private RedTeacherRepository redTeacherRepository;

    @Around("@annotation(com.young.springdemo.config.red.RedPerson)")
    private Object redValidate(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        log.info("切面验证方法[{}]中红名单信息", signature.getMethod().getName());
        RedPerson annotation = signature.getMethod().getAnnotation(RedPerson.class);//获取到注解
        int index = annotation.index();//获取到第index个参数是红名单用户
        Object[] args = point.getArgs();//获取所有参数
        if (args.length <= index) index = 0;//如果指定红名单名称大于总数,则取默认值,第一个
        String userName = args[index].toString();
        List<RedTeacherEntity> list = redTeacherRepository.findByRedTeacher(userName);
        String location = point.getTarget().toString() + "." + signature.getMethod().getName();
        if (list != null && list.size() != 0) {
            throw  new RedTeacherException(location);
        }
        return point.proceed();
    }
}
